package com.nf.health.app.activity.global;

import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

import com.nf.health.app.Constants;
import com.nf.health.app.R;
import com.nf.health.app.http.Apis;
import com.nf.health.app.mine.activity.IntroductionActivity;
import com.nf.health.app.models.AJAXLogin;
import com.nf.health.app.utils.ActivityUtils;
import com.nf.health.app.utils.Code;
import com.nf.health.app.utils.PreferenceHelper;
import com.nf.health.app.utils.Util;
import com.nf.health.app.utils.ViewUtil;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * @author Ian
 * @ClassName: RegistrationActivity
 * @Description: 注
 * @date 2015-11-4 上午11:03:09
 */
public class RegistrationActivity extends BaseActivity implements
        OnClickListener {
    private EditText et_teleNum, et_verification_code, et_new_password,
            et_submit_password;
    private Button iv_success_submit, btn_get_code;
    private String phone;
    private View tv_protocol;
    private CheckBox cb_protocol;
    private TimeCount timeCount;

    String pwd1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTitleBar(R.layout.titlebar_base);
        setContent(R.layout.activity_registration);
        TextView titleTV = (TextView) findViewById(R.id.titlebar_title_tv);
        titleTV.setText("注册");
        et_teleNum = (EditText) findViewById(R.id.et_teleNum);
        et_verification_code = (EditText) findViewById(R.id.et_verification_code);
        et_new_password = (EditText) findViewById(R.id.et_new_password);
        et_submit_password = (EditText) findViewById(R.id.et_submit_password);
        iv_success_submit = (Button) findViewById(R.id.iv_success_submit);
        btn_get_code = (Button) findViewById(R.id.btn_get_code);
        tv_protocol = ViewUtil.getView(this, R.id.tv_protocol);
        cb_protocol = ViewUtil.getView(this, R.id.cb_protocol);

        initListener();

        timeCount = new TimeCount(60000, 1000);
    }

    //计时重发
    private class TimeCount extends CountDownTimer {
        /**
         * @param millisInFuture    计时器执行的时长
         * @param countDownInterval 执行一次的时间间隔
         */
        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            btn_get_code.setText("重发（" + millisUntilFinished / 1000 + "秒）");
//        	et_verification_code.setFocusable(true);
//        	et_verification_code.requestFocus();
            btn_get_code.setClickable(false);
        }

        @Override
        public void onFinish() {
            resetCodeBtn();
        }

    }

    private void resetCodeBtn() {
        btn_get_code.setClickable(true);
        btn_get_code.setText("获取验证码");
    }

    private void initListener() {
        iv_success_submit.setOnClickListener(this);
        btn_get_code.setOnClickListener(this);
        tv_protocol.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Bundle bundlePrivacy = new Bundle();
                bundlePrivacy.putString("type", "privacy");
                ActivityUtils.showActivity(RegistrationActivity.this, IntroductionActivity.class, bundlePrivacy);
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {

            case R.id.iv_success_submit:
                if (!cb_protocol.isChecked()) {
                    showToast("你没有同意服务条款");
                    return;
                }

                phone = et_teleNum.getText().toString();
                pwd1 = et_new_password.getText().toString();
                String pwd2 = et_submit_password.getText().toString();
                String currentCode = et_verification_code.getText().toString();

                if (TextUtils.isEmpty(phone)) {
                    showToast(R.string.phone_not_blank);
                    break;
                }
                if (!Util.isPhone(phone)) {
                    showToast(R.string.phone_error_prompt);
                    break;
                }
                if (TextUtils.isEmpty(pwd1)) {
                    showToast(R.string.pwd_not_blank);
                    break;
                }
                if (TextUtils.isEmpty(currentCode)) {
                    showToast(R.string.auth_code_error_prompt);
                    break;
                }
                if (!Util.isPassword(pwd1)) {
                    showToast(R.string.pwd_style_prompt);
                    break;
                }
                if (!pwd1.equals(pwd2)) {
                    showToast(R.string.pwd_inconsistency);
                    break;
                }
//				provider.requestMSGCodeCode(phone, currentCode,"register", "yanzheng");
                provider.requestPhoneRegister(phone, pwd1, currentCode, Constants.SMS_REGISTER, "phoneRegister");
                break;
            case R.id.btn_get_code:
                phone = et_teleNum.getText().toString();
                if (TextUtils.isEmpty(phone)) {
                    showToast(R.string.phone_not_blank);
                    break;
                }
                if (!Util.isPhone(phone)) {
                    showToast(R.string.phone_error_prompt);
                    break;
                }
                timeCount.start();
                Constants.LOCAL_CODE = Code.getInstance().getCode();
//			if(LogUtil.IS_DEBUG){
//				et_verification_code.setText(Constants.LOCAL_CODE);
//			}
                provider.requestMSGCode(phone, Constants.SMS_REGISTER, "verifycode");

                break;
            default:
                break;
        }
        super.onClick(v);
    }


    @Override
    public void handleActionSuccess(String actionName, Object object) {
        super.handleActionSuccess(actionName, object);
        if (actionName.equals("verifycode")) {
            if (Apis.HOST_COMMON.contains("test.")) {
                //返回验证码, 自动添加到框里, 发包时注释掉
                String code = null;
                try {
                    code = new JSONObject((String) object).optJSONObject("data").optString("verifycode");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                et_verification_code.setText(code);
            }

            hideLoading();
            showToast("验证码发送成功！");
        } else if (actionName == "phoneRegister") {
            hideLoading();
            String phoneReginster = (String) object;
            if (phoneReginster.equals("0")) {
                PreferenceHelper.putString(PreferenceHelper.USERNAME, et_teleNum.getText().toString());
                PreferenceHelper.putString(PreferenceHelper.PASSWORD, et_new_password.getText().toString());
                //关闭注册页和登录页
                provider.requestAJAX(et_teleNum.getText().toString(), Util.encode(et_new_password.getText().toString()), "requestAJAX");
            } else {
                showToast("注册失败！");
            }
        } else if ("requestAJAX".equals(actionName)) {
            AJAXLogin ajaxLogin = (AJAXLogin) object;
            PreferenceHelper.putString(PreferenceHelper.TOKEN, ajaxLogin.getCode());
            //新的token 以后每次请求必须带上 直接写在HttpRequestProvider中 2016.06.04
            PreferenceHelper.putString(PreferenceHelper.ACCESS_TOKEN, ajaxLogin.getAccess_token());
            PreferenceHelper.putBoolean(PreferenceHelper.ISLOGIN, false);
            PreferenceHelper.putBoolean(PreferenceHelper.REGISTER_INFO_COMPLETE, false);
//            AppManager.getAppManager().finishAllActivity();
            Bundle bundle = new Bundle();
            bundle.putString("type", getIntent().getStringExtra("type"));
            ActivityUtils.showActivity(this, RegisterNickActivity.class, bundle);
            finish();
        }
    }

    public static String encode(String code) {
        if (TextUtils.isEmpty(code)) {
            return "";
        }
        StringBuffer rs = new StringBuffer("");
        for (int i = 0; i < code.length(); i++) {
            rs.append("$").append((int) code.charAt(i)).append("1").append(";");
        }
        return new String(rs);
    }

    @Override
    public void handleActionStart(String actionName, Object object) {
        super.handleActionStart(actionName, object);
        showLoading();
    }

    @Override
    public void handleActionFinish(String actionName, Object object) {
        super.handleActionFinish(actionName, object);
        hideLoading();
    }

}
